package com.sesum;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Sesum extends Activity {
	
	static String TAG = "Sesum";
	static String NameBBDD = "Sesum";
	static String login = "";
	static String password = "";
	static String car_registration = "";
	static String state = "";
	
	//Estados
	static String ACTIVATE_STATE = "1";
	static String DESACTIVATE_STATE = "2";
	
	
	
	
    protected boolean login(String login, String password) {
		// TODO Auto-generated method stub
    	
    	JSONObject user = Actions.login(login, password);
    	if (user != null){
    		if (!exitsUserBBDD(user))
    			insertUserBBDD(user);
    		return true;
    	}else
    		return false;
    	

	}
    
    protected boolean logout(String login) {
		// TODO Auto-generated method stub
    	boolean result = dropUserBBDD(login);
    	if (!result){
    		Log.e(TAG, "Error al desconectar el usuario; "+login);
    	}else{
    		Log.e(TAG, "Usuario desconectado correctamente ");
    	}
    	return result;
	}
    
    protected boolean signup(String login, String password, String carRegistration, String state) {
    	String result = Actions.register(login, password, carRegistration, state);
    	if (result != null && "OK".equals(result)){
    		boolean resultLogin = login(login,password);
    		return resultLogin;
    	}else
    		return false;

	}
    
    protected boolean decline(String login, String password) {
    	String result = Actions.decline(login, password);
    	if (result != null && "OK".equals(result)){
    		dropUserBBDD(login);
    		return true;
    	}else
    		return false;

	}
    
    protected void insertUserBBDD(JSONObject userData) {
        if (userData != null){
	        //Abrimos la base de datos 'Sesum' en modo escritura
	        UserSQLiteOpenHelper usdbh =
	            new UserSQLiteOpenHelper(this, NameBBDD, null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	String login = "";
	        	String password = "";
	        	String car_registration = "";
	        	String state = "";
	        	
	        	//Recuperamos car_registration y state
	        	try {
	        		car_registration = userData.getString("car_registration");
	        		state = userData.getString("state");
	        		
	        	} catch (Exception e) {
	        		Log.e(TAG, "No se ha podido recuperar car_registration ni state: "+e.toString());
	        	}
	        	
	        	//Recuperamos login y password e insertamos en bbdd
	        	try {
	        		login = userData.getString("login");
	        		password = userData.getString("password");
	        		//Insertamos los datos en la tabla Usuarios
	        		db.execSQL("INSERT INTO users (login, password, car_registration, state) " +
	        				"VALUES ('" + login + "', '" + password +"', '" + car_registration +"', '" + state +"')");
				} catch (Exception e) {
					Log.e(TAG, "No se ha podido insertar el usuario y password en bbdd: "+e.toString());
				}
				db.close();
	        	
	        	
	        }
        }

	}
    
    protected boolean exitsUserBBDD(JSONObject userData) {
    	boolean result = false;
        if (userData != null){
	        //Abrimos la base de datos 'Sesum' en modo escritura
	        UserSQLiteOpenHelper usdbh =
	            new UserSQLiteOpenHelper(this, NameBBDD, null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	String login = "";
	        	
	        	//Recuperamos login y password e insertamos en bbdd
	        	try {
	        		login = userData.getString("login");
	        		
	        		Cursor c = db.rawQuery("SELECT * FROM users WHERE login = "+login, null);
	        		if (c.getCount() == 1)
	        			result = true;
        			else
        				result = false;
				} catch (Exception e) {
					Log.e(TAG, "No se ha recuperar el usuario y password en bbdd: "+e.toString());
				}
				db.close();
	        	
	        	
	        }
        }
        return result;

	}
    
    protected HashMap<String, String> loadUserBBDD() {
    	HashMap<String, String> user = null;
        //Abrimos la base de datos 'Sesum' en modo escritura
        UserSQLiteOpenHelper usdbh =
            new UserSQLiteOpenHelper(this, NameBBDD, null, 1);
        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	try {
	        		Cursor c = db.rawQuery("SELECT * FROM users", null);
	        		if (c.getCount() >= 1){
	        			c.moveToFirst();
	        			user = new HashMap<String, String>();
		        		user.put("login", c.getString(c.getColumnIndex("login")));
		        		user.put("password", c.getString(c.getColumnIndex("password")));
		        		user.put("car_registration", c.getString(c.getColumnIndex("car_registration")));
		        		user.put("state", c.getString(c.getColumnIndex("state")));
        			
	        			
	        		}else
        				user = null;
				} catch (Exception e) {
					Log.e(TAG, "No se ha recuperar el usuario de bbdd: "+e.toString());
				}
				db.close();
	        	
	        	
	        }
        return user;

	}
    
    
    protected boolean dropUserBBDD(String login) {
        if (login != null){
	        //Abrimos la base de datos 'Sesum' en modo escritura
	        UserSQLiteOpenHelper usdbh =
	            new UserSQLiteOpenHelper(this, NameBBDD, null, 1);
	        SQLiteDatabase db = usdbh.getWritableDatabase();
	        
	        if(db != null)
	        {
	        	//Recuperamos login y password e insertamos en bbdd
	        	try {
	        		//Borramos los datos en la tabla Usuarios
	        		db.execSQL("DELETE FROM users WHERE login = '"+login+"'");
	        		return true;
				} catch (Exception e) {
					Log.e(TAG, "No se ha podido borrar el usuario en bbdd: "+e.toString());
				}
				db.close();
	        	
	        	
	        }
	        return false;
        }
        return false;

	}
    
    protected boolean changePassword(String login, String oldPassword, String newPassword) {
    	String result = Actions.changePassword(login, oldPassword, newPassword);
    	if (result != null && "OK".equals(result)){
    		dropUserBBDD(login);
    		login(login, newPassword);
    		return true;
    	}else
    		return false;

	}
    
    protected boolean existsLogin(String login) {
    	String result = Actions.existLogin(login);
    	if (result != null && "OK".equals(result)){
    		return true;
    	}else
    		return false;
	}
    
    protected boolean updateState(String login, String password, String carRegistration, String state) {
    	String result = Actions.updateState(login, password, carRegistration, state);
    	if (result != null && "OK".equals(result)){
    		return true;
    	}else
    		return false;
	}
    
    protected boolean updateCarRegistration(String login, String password, String carRegistration, String state) {
    	String result = Actions.updateCarRegistration(login, password, carRegistration, state);
    	if (result != null && "OK".equals(result)){
    		return true;
    	}else
    		return false;
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.general, menu);
        menu.add("Prueba");
        return true;

    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.disconect:
            dropUserBBDD(login);
            finish();
			Intent intent = new Intent(getApplicationContext(), Login.class);
			startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}